//
//  LBMarqueeLabel2.m
//  Test
//
//  Created by liubo on 2023/7/22.
//

#import "LBMarqueeLabel.h"

@interface LBMarqueeLabel () <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) LBMaqueeLabelConfig *configuration;

@property (nonatomic, assign) CGFloat secondOriginx;

@property (nonatomic, weak) CADisplayLink *link;

@property (nonatomic, assign) BOOL isLink;
 
@end

@implementation LBMarqueeLabel

- (instancetype)initWithFrame:(CGRect)frame
                configuration:(nonnull LBMaqueeLabelConfig *)configuration
{
    if (self =  [super initWithFrame:frame]) {
        self.configuration = configuration;
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI
{
    [self addSubview:self.scrollView];
    CGFloat origin = 0;
    for (int i = 0; i < 2; i ++) {
        NSString *string = self.configuration.text;
        CGFloat width = [string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, self.bounds.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.configuration.font} context:nil].size.width;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(origin + i * self.configuration.itemSpace, 0, width, self.bounds.size.height)];
        label.font = self.configuration.font;
        label.textColor = self.configuration.textColor;
        label.text = self.configuration.text;
        origin = CGRectGetMaxX(label.frame);
        [self.scrollView addSubview:label];
        if (i == 1) {
            self.secondOriginx = CGRectGetMinX(label.frame);
            self.scrollView.contentSize = CGSizeMake(CGRectGetMaxX(label.frame), 0);
        }
    }
}

- (void)linkStart
{
    self.isLink = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.configuration.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateContentOffset)];
        [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        self.link = link;
    });
}

- (void)animationStart
{
    NSTimeInterval duration = self.secondOriginx / self.configuration.rate;
    [UIView animateWithDuration:duration delay:self.configuration.delayTime options:UIViewAnimationOptionCurveLinear animations:^{
        [self.scrollView setContentOffset:CGPointMake(self.secondOriginx, 0) animated:NO];
    } completion:^(BOOL finished) {
        [self.scrollView setContentOffset:CGPointZero];
        [self animationStart];
    }];
}

- (void)updateContentOffset
{
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + self.configuration.rate, 0)];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.isLink) {
        return;
    }
    if (scrollView.contentOffset.x >= self.secondOriginx) {
        scrollView.contentOffset = CGPointMake(0, 0);
        [self.link invalidate];
        self.link = nil;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.configuration.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self linkStart];
        });
    }
}

#pragma mark - lazy load

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
     }
    return _scrollView;
}

@end
